import bcrypt from 'bcryptjs'
import { Router } from 'express'
import { sign } from '../../utils/token'
import { find } from '../../db/dao'
import { USER, UserData, STUDENT } from '../../db/model'

const router = Router()

router.post('/login', (req, res) => {
  const { account, password, identity } = req.body
  // 查询数据库
  Promise.all([
    find(STUDENT, { account }), // 详情表
    find(USER, { account, identity }) // 账号表
  ]).then(async (users: Array<any>) => {
    if (users.length === 0) {
      return res.status(403).send('用户不存在')
    }
    const student: UserData = users[0][0]
    const user: UserData = users[1][0]
    // 密码匹配
    const isMatch = await bcrypt.compare(password, user.password)
    if (!isMatch) {
      return res.status(403).send('密码错误')
    }
    // 签发token
    const token = await sign({
      account: user.account,
      name: student.name,
      identity,
      sex: student.sex,
      grade: student.grade,
      class: student.class,
      dept: student.dept,
      position: student.position
    })
    res.status(200).json({
      success: true,
      token: `Bearer ${token}`
    })
  }).catch(() => {
    res.status(500).end()
  })
})

export default router
